package com.aviccxzx.smarthome.UserModule;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.aviccxzx.smarthome.DeviceModule.GosDeviceModuleBaseActivity;
import com.aviccxzx.smarthome.MsgID;
import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.entity.DeleteDevMove;
import com.aviccxzx.smarthome.entity.DoorMsg;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.netutil.msg.MsgCenter;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.utils.ChangeNameDialogUtil;
import com.aviccxzx.smarthome.utils.DialogUtil;
import com.gizwits.gizwifisdk.api.GizWifiCentralControlDevice;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.api.GizWifiSDK;
import com.gizwits.gizwifisdk.enumration.GizDeviceSharingUserRole;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.gizwifisdk.listener.GizWifiCentralControlDeviceListener;
import com.gizwits.gizwifisdk.listener.GizWifiDeviceListener;
import com.gizwits.gizwifisdk.listener.GizWifiSDKListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.aviccxzx.smarthome.fragment.DeviceListFragment.isFromDeviceList;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.mDevice;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.subList;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.tagSet;


/**
 * Created by joey on 206/11/17.
 */
public class SmokeActivity extends GosDeviceModuleBaseActivity implements View.OnClickListener {
    TextView door_name, title_name_tv, door_electricity, smoke_switch_tv, door_mac;
    String name = "";
    String macaddress = "";
    String netStatus = "";
    boolean alarm;
    String pos = "";
    ListView doormsg_list;
    DoorAdapter adapter = null;
    List<DoorMsg.DataBean> msgList1 = null;
    List<DoorMsg.DataBean> msgList = new ArrayList<>();
    GizWifiDevice mdevice = null;
    CheckBox smoke_switch;
    TextView smoke_state_tv;
    ImageView smoke_cion_img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setContentView(R.layout.smoke_lay_v19);
        } else {
        }
        initView();
        getHistory();
    }

    private void getHistory() {
        progressDialog.show();
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Call<DoorMsg> call = service.getDataHistory(macaddress);
        call.enqueue(new Callback<DoorMsg>() {
            @Override
            public void onResponse(Call<DoorMsg> call, Response<DoorMsg> response) {
                if (response.body() != null && response.body().getData() != null)
                    msgList1 = response.body().getData();
                if (msgList1 != null && msgList1.size() > 0) {
                    for (DoorMsg.DataBean data : msgList1) {
                        if (data.getValue().equals("1")) {
                            msgList.add(data);
                        }
                    }
                    //                    Collections.reverse(msgList);
                    adapter = new DoorAdapter();
                    doormsg_list.setAdapter(adapter);
                    progressDialog.dismiss();
                } else {
                    App.getApp().showToast("没有历史消息");
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onFailure(Call<DoorMsg> call, Throwable t) {
                progressDialog.dismiss();
            }
        });

    }

    private void initView() {
        findViewById(R.id.ll_title_left_view).setOnClickListener(this);
        findViewById(R.id.smoke_on).setOnClickListener(this);
        door_name = (TextView) findViewById(R.id.door_name);
        door_electricity = (TextView) findViewById(R.id.door_electricity);
        title_name_tv = (TextView) findViewById(R.id.title_name_tv);
        doormsg_list = (ListView) findViewById(R.id.doormsg_list);
        smoke_switch = (CheckBox) findViewById(R.id.smoke_switch);
        smoke_switch_tv = (TextView) findViewById(R.id.smoke_switch_tv);
        smoke_state_tv = (TextView) findViewById(R.id.smoke_state_tv);
        smoke_cion_img = (ImageView)findViewById(R.id.smoke_cion_img);
        //点击修改名称
        findViewById(R.id.device_info).setOnClickListener(this);
        findViewById(R.id.door_name).setOnClickListener(this);
        findViewById(R.id.delete_doorlock).setOnClickListener(this);
        netStatus = getIntent().getStringExtra("netStatus");
        name = getIntent().getStringExtra("deviceName");
        macaddress = getIntent().getStringExtra("deviceMac");
        alarm = getIntent().getBooleanExtra("alarm", false);
        door_mac = (TextView) findViewById(R.id.door_mac);
        door_mac.setText("ID:" + macaddress);
        if(!TextUtils.isEmpty(netStatus)){
            smoke_state_tv.setText("掉线");
            smoke_state_tv.setTextColor(getResources().getColor(R.color.red));
        }
        if (alarm) {
            smoke_state_tv.setText("异常报警");
            smoke_state_tv.setTextColor(getResources().getColor(R.color.red));

            smoke_switch.setChecked(true);
        }
        if (!TextUtils.isEmpty(name)) {
            title_name_tv.setText(name);
            door_name.setText(name);
        }
        for (GizWifiDevice device : subList) {
            if (device.getMacAddress().equals(macaddress)) {
                mdevice = device;
            }
        }
        if (mdevice != null) {
            //订阅设备
            //监听上报
            mdevice.setListener(subListener);
            mdevice.setSubscribe(MsgID.PS_SMOKE, true);
        }
        Set<String> newSmoke = spf.getStringSet("newSmoke", null);
        if (newSmoke.contains(mdevice.getMacAddress().toString())){
            smoke_cion_img.setImageResource(R.mipmap.smoke_icon_hm);
        }else {
            smoke_cion_img.setImageResource(R.mipmap.smoke_icon);
        }
    }

    // 订阅实现回调
    GizWifiDeviceListener subListener = new GizWifiDeviceListener() {
        @Override
        public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice
                device, boolean isSubscribed) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                // 订阅或解除订阅成功
                mdevice.setListener(deviceListener);
                mdevice.getDeviceStatus(null);
            } else {
                // 失败
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }
    boolean standard;
    boolean getVersion = false;//判断是否获取到数据点信息
    /**
     * 获取上报的设备信息
     */
    private GizWifiDeviceListener deviceListener = new GizWifiDeviceListener() {
        @Override
        public void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, Object> dataMap, int sn) {
            super.didReceiveData(result, device, dataMap, sn);
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                if (dataMap.get("data") != null) {
                    ConcurrentHashMap<String, Object> map = (ConcurrentHashMap<String, Object>) dataMap.get("data");
                    if (map.get("SoftWareVersion") != null) {
                        byte[] hard = (byte[]) map.get("SoftWareVersion");
                        String hardVi = new String(hard);
                        if (hardVi.contains("2")) {
                            //TODO
                            //新烟感时
                            smoke_cion_img.setImageResource(R.mipmap.smoke_icon_hm);
                        } else {
                            //旧烟感时
                            smoke_cion_img.setImageResource(R.mipmap.smoke_icon);
                        }
                    }
                    byte[] hard = (byte[]) map.get("HardWareVersion");
                    String hardVi = new String(hard);
                    if (hardVi.endsWith("0")){
                        //专业版 显示灵敏度调节
                        standard = false;
                    }else {
                        //标准版
                        standard = true;
                    }
                    getVersion = true;
                    Boolean alarmState = (Boolean) map.get("SmokeAlarm");
                    if (alarmState != null && alarmState) {
                        smoke_state_tv.setText("异常报警");
                        smoke_state_tv.setTextColor(getResources().getColor(R.color.red));

                        smoke_switch.setChecked(true);
                    } else {
                        smoke_state_tv.setText("正常");
                        smoke_state_tv.setTextColor(getResources().getColor(R.color.white));

                        smoke_switch.setChecked(false);
                    }
                    boolean powerAlarm = (boolean) map.get("PowerAlarm");
                    int electricity = (int) map.get("Electricity");
                    if (powerAlarm||electricity<20) {
                        //低电量提示
                        smoke_switch_tv.setText("电量低!");
                        smoke_switch_tv.setTextColor(getResources().getColor(R.color.red));
                    }else {
                        smoke_switch_tv.setText(electricity + "%");
                    }
                }
            }
        }
    };

    String deviceName, uid, token = "";

    @Override
    public void onClick(View view) {
        uid = spf.getString("Uid", "");
        token = spf.getString("Token", "");
        switch (view.getId()) {
            case R.id.ll_title_left_view:
                finish();
                break;
            case R.id.device_info:
                if (getVersion) {
                    Intent intent = new Intent(this,DeviceInfoActivity.class);
                    intent.putExtra("id",macaddress);
                    intent.putExtra("standard",standard);
                    intent.putExtra("class",3);
                    startActivity(intent);
                }else {
                    App.getApp().showToast("稍等几秒钟，设备正在启动中");
                }

                break;
            case R.id.smoke_on:
                if (smoke_switch.isChecked()) {
                    //解除报警
                    ConcurrentHashMap<String, Object> data = new ConcurrentHashMap<>();
                    data.put("Cancel_alarm", true);
                    mdevice.write(data, 0);
                    mdevice.setListener(getListener);
                    progressDialog.show();
                }
                break;
            case R.id.door_name:

                new ChangeNameDialogUtil(SmokeActivity.this, "修改设备名称", new ChangeNameDialogUtil.SureInterfance() {
                    @Override
                    public void sureTodo(String name) {
                        //确定修改 处理方案
                        App.getApp().showToast(name);
                        deviceName = name;
                        mdevice.setCustomInfo("", name);
                        mdevice.setListener(getGizWifiDeviceListener());
                        progressDialog.show();
                    }
                }).showSelfDialog();
                break;
            case R.id.delete_doorlock:
                    new DialogUtil(SmokeActivity.this, true, true, "确认删除子设备吗", "取消", "确定", new DialogUtil.SureInterfance() {
                        @Override
                        public void sureTodo() {
                            if (mdevice.getSharingRole() != null && mdevice.getSharingRole().equals(GizDeviceSharingUserRole.GizDeviceSharingGuest)) {
                                deleteMove(0);
                            } else {
                                deleteMove(1);
                            }
                        }

                        @Override
                        public void cancle() {

                        }
                    }).showCustomDialog();
                break;
        }
    }


    // 实现回调
    GizWifiDeviceListener getListener = new GizWifiDeviceListener() {
        @Override
        public void didReceiveData(GizWifiErrorCode result, GizWifiDevice
                device, ConcurrentHashMap<String, Object> dataMap, int sn) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                if (sn == 0) {
                    // 浓度设置成功
                    // 解除报警成功
                    smoke_state_tv.setText("正常");
                    smoke_state_tv.setTextColor(getResources().getColor(R.color.white));

                    smoke_switch.setChecked(false);
                }
                MsgCenter.fireNull("update_alarm",mdevice.getMacAddress());
            } else {
                if (sn == 0) {
                    //恢复之前的初试浓度
                    smoke_state_tv.setText("异常报警");
                    smoke_state_tv.setTextColor(getResources().getColor(R.color.red));

                    smoke_switch.setChecked(true);
                }
                MsgCenter.fireNull("update_alarmset",mdevice.getMacAddress());
            }
            progressDialog.dismiss();
        }
    };

    /**
     * 修改名字回调
     *
     * @param result 错误码
     * @param device 当前设备
     */
    @Override
    public void didSetCustomInfo(GizWifiErrorCode result, GizWifiDevice device) {
        super.didSetCustomInfo(result, device);
        progressDialog.dismiss();
        if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
            // 修改成功
            App.getApp().showToast("修改成功");
            door_name.setText(deviceName);
            //                finish();
        } else {
            //修改失败
            App.getApp().showToast("修改失败");
        }
    }

    // 实现回调
    GizWifiDeviceListener mListener = new
            GizWifiCentralControlDeviceListener() {
                @Override
                public void didUpdateSubDevices(GizWifiCentralControlDevice device, GizWifiErrorCode result,
                                                List<GizWifiDevice> subDeviceList) {
                    Log.i("addlogg", "smoke===" + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(System.currentTimeMillis())));
                    if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS || result == GizWifiErrorCode.GIZ_SDK_SUBDEVICE_INVALID) {
                        // 删除成功
                      GizWifiSDK.sharedInstance().setListener(unbindListener);
                        GizWifiSDK.sharedInstance().unbindDevice(uid, token,
                                mdevice.getDid());
                    } else {
                        // 删除失败
//                        progressDialog.dismiss();
//                        App.getApp().showToast("网络延迟，请稍候再试");

                        GizWifiSDK.sharedInstance().setListener(unbindListener);
                        GizWifiSDK.sharedInstance().unbindDevice(uid, token,
                                mdevice.getDid());
                    }
                }
            };
    GizWifiSDKListener unbindListener = new GizWifiSDKListener() {
        @Override
        public void didUnbindDevice(GizWifiErrorCode result, String did) {
            super.didUnbindDevice(result, did);
                if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                    //调用接口使该设备处于布防状态
//                    setOpen();
                    // 解绑成功
                    isFromDeviceList = false;
                    tagSet.remove(mdevice.getMacAddress());
                    tagSet.add(uid);
                    JPushInterface.setTags(SmokeActivity.this, 0, tagSet);
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            /**
                             *要执行的操作
                             */
                            finish();
                        }
                    }, 2000);
                } else {
                    // 解绑失败
                    progressDialog.dismiss();
                    App.getApp().showToast("删除失败，请稍候重试");
                }
        }
    };

    public void deleteMove(int admin) {
        progressDialog.show();
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Call<DeleteDevMove> call = service.unbundSub(mdevice.getMacAddress(), admin);
        call.enqueue(new Callback<DeleteDevMove>() {
            @Override
            public void onResponse(Call<DeleteDevMove> call, Response<DeleteDevMove> response) {
                if (response != null && response.body() != null) {
                    int code = response.body().getCode();
                    if (code == 4) {
                        if (mdevice.getSharingRole() != null && mdevice.getSharingRole().equals(GizDeviceSharingUserRole.GizDeviceSharingGuest)) {
                            //分享的设备只解绑不删除
                            GizWifiSDK.sharedInstance().setListener(unbindListener);
                            GizWifiSDK.sharedInstance().unbindDevice(uid, token,
                                    mdevice.getDid());
                        } else {
                            mDevice.setListener(mListener);
                            mDevice.deleteSubDevice(mdevice);
                        }

                        tagSet.remove(mdevice.getMacAddress());
                        JPushInterface.setTags(SmokeActivity.this, 0, tagSet);
                    } else {
                        progressDialog.dismiss();
                        App.getApp().showToast("接口删除失败");
                    }
                }
            }

            @Override
            public void onFailure(Call<DeleteDevMove> call, Throwable t) {

            }
        });
    }

    HashMap<Integer, View> mHashMap = new HashMap<>();

    public class DoorAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return msgList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup viewGroup) {
            ViewHolder holder = null;
            if (mHashMap.get(i) == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(SmokeActivity.this).inflate(R.layout.doormsg_listitem_lay, viewGroup, false);
                mHashMap.put(i, convertView);
                convertView.setTag(holder);
            } else {
                convertView = mHashMap.get(i);
                holder = (ViewHolder) convertView.getTag();
            }

            holder.msg_name = (TextView) convertView.findViewById(R.id.msg_name);
            holder.msg_time = (TextView) convertView.findViewById(R.id.msg_time);

            DoorMsg.DataBean data = msgList.get(i);
            if (data != null) {
                holder.msg_name.setText("烟雾报警器报警");
                holder.msg_time.setText(data.getCtime());
            }
            progressDialog.dismiss();
            return convertView;
        }

        public class ViewHolder {
            TextView msg_name, msg_time;
        }
    }
}
